This case study is about apt salary band determination. When an organization decides to hire a new employee and the question is how much salary does this person deserves based on their credentials, demographic/anagraphic details and experience?
Based on the "Census Income" data of 32,561 professionals from around the world. We will try to learn when a candidate deserves a salary greater than $50K and when they does not.
In below case study I will discuss the step by step approach to create a Machine Learning predictive model in such scenarios. You can use this flow as a template to solve any supervised ML classification problem.
The flow of the case study is as below:
I know its a long list!! Take a deep breath... and let us get started!
This is one of the most important steps in machine learning! You must understand the data and the domain well before trying to apply any machine learning algorithm.
The data has one file "SalaryData.csv". This file contains the historical census data data of 32,561 working professionals from all over the world indicating whether they earn more than $50K or not.
The goal is to learn from this data and predict if a new candidate can be hired with a salary more than $50K or not?
The business meaning of each column in the data is as below
More detailed information about this dataset can be found here
# Supressing the warning messages
import warnings
warnings.filterwarnings('ignore')
# Reading the dataset
import pandas as pd
import numpy as np
SalaryData=pd.read_csv('/Users/farukh/Python Case Studies/SalaryData.csv', encoding='latin')
print('Shape before deleting duplicate values:', SalaryData.shape)
# Removing duplicate rows if any
SalaryData=SalaryData.drop_duplicates()
print('Shape After deleting duplicate values:', SalaryData.shape)
# Printing sample data
# Start observing the Quantitative/Categorical/Qualitative variables
SalaryData.head(10)
Based on the problem statement you can understand that we need to create a supervised ML classification model, as the target variable is categorical.
%matplotlib inline
# Creating Bar chart as the Target variable is Categorical
GroupedData=SalaryData.groupby('SalaryGT50K').size()
GroupedData.plot(kind='bar', figsize=(4,3))
The data distribution of the target variable is satisfactory to proceed further. There are sufficient number of rows for each category to learn from.
This step is performed to guage the overall data. The volume of data, the types of columns present in the data. Initial assessment of the data should be done to identify which columns are Quantitative, Categorical or Qualitative.
This step helps to start the column rejection process. You must look at each column carefully and ask, does this column affect the values of the Target variable? For example in this case study, you will ask, does this column affect the salary earned by the employee? If the answer is a clear "No", then remove the column immediately from the data, otherwise keep the column for further analysis.
There are four commands which are used for Basic data exploration in Python
# Looking at sample rows in the data
SalaryData.head()
# Observing the summarized information of data
# Data types, Missing values based on number of non-null values Vs total rows etc.
# Remove those variables from data which have too many missing values (Missing Values > 30%)
# Remove Qualitative variables which cannot be used in Machine Learning
SalaryData.info()
# Looking at the descriptive statistics of the data
SalaryData.describe(include='all')
# Finging unique values for each column
# TO understand which column is categorical and which one is Continuous
# Typically if the numer of unique values are < 20 then the variable is likely to be a category otherwise continuous
SalaryData.nunique()
Based on the basic exploration above, you can now create a simple report of the data, noting down your observations regaring each column. Hence, creating a initial roadmap for further analysis.
The selected columns in this step are not final, further study will be done and then a final list will be created
We can spot a categorical variable in the data by looking at the unique values in them. Typically a categorical variable contains less than 20 Unique values AND there is repetition of values, which means the data can be grouped by those unique values.
Based on the Basic Data Exploration above, we have spotted eight categorical predictors in the data
Categorical Predictors: 'relationship', 'race', 'sex', 'native_country', workclass', 'education', 'marital_status',and 'occupation'
We use bar charts to see how the data is distributed for these categorical columns.
# Plotting multiple bar charts at once for categorical variables
# Since there is no default function which can plot bar charts for multiple columns at once
# we are defining our own function for the same
def PlotBarCharts(inpData, colsToPlot):
%matplotlib inline
import matplotlib.pyplot as plt
# Generating multiple subplots
fig, subPlot=plt.subplots(nrows=1, ncols=len(colsToPlot), figsize=(40,6))
fig.suptitle('Bar charts of: '+ str(colsToPlot))
for colName, plotNumber in zip(colsToPlot, range(len(colsToPlot))):
inpData.groupby(colName).size().plot(kind='bar',ax=subPlot[plotNumber])
#####################################################################
# Calling the function
PlotBarCharts(inpData=SalaryData, colsToPlot=['workclass', 'education', 'marital_status','occupation'])
#####################################################################
# Calling the function
PlotBarCharts(inpData=SalaryData, colsToPlot=['relationship', 'race', 'sex', 'native_country'])
These bar charts represent the frequencies of each category in the Y-axis and the category names in the X-axis.
The ideal bar chart looks like the chart of "occupation" column. Where each category has comparable frequency. Hence, there are enough rows for each category in the data for the ML algorithm to learn.
If there is a column which shows too skewed distribution like "native_country" where there is only one dominant bar and the other categories are present in very low numbers. These kind of columns may not be very helpful in machine learning. We confirm this in the correlation analysis section and take a final call to select or reject the column.
In this data, all the categorical columns except "native_country" have satisfactory distribution to be considered for machine learning.
Selected Categorical Variables: All the categorical variables are selected except "native_country".
'workclass', 'education', 'marital_status','occupation', 'relationship', 'race', 'sex'
Based on the Basic Data Exploration, There are five continuous predictor variables 'age', 'fnlwgt','capital_gain','capital.loss', and 'hours_per_week'
# Plotting histograms of multiple columns together
# Observe that ApplicantIncome and CoapplicantIncome has outliers
SalaryData.hist(['age', 'fnlwgt','capital_gain','capital.loss','hours_per_week'], figsize=(18,10))
Histograms shows us the data distribution for a single continuous variable.
The X-axis shows the range of values and Y-axis represent the number of values in that range. For example, in the above histogram of "age", there are around 6200 rows in data that has a age between 40 to 45.
The ideal outcome for histogram is a bell curve or slightly skewed bell curve. If there is too much skewness, then outlier treatment should be done and the column should be re-examined, if that also does not solve the problem then only reject the column.
Selected Continuous Variables:
Outliers are extreme values in the data which are far away from most of the values. You can see them as the tails in the histogram.
Outlier must be treated one column at a time. As the treatment will be slightly different for each column.
Why I should treat the outliers?
Outliers bias the training of machine learning models. As the algorithm tries to fit the extreme value, it goes away from majority of the data.
There are below two options to treat outliers in the data.
Below we are finding out the most logical value to be replaced in place of outliers by looking at the histogram.
# Finding nearest values to 600000 mark
SalaryData['fnlwgt'][SalaryData['fnlwgt']>599000].sort_values()
Above result shows the nearest logical value is 599629, hence, replacing any value above 600000 with it.
# Replacing outliers with nearest possibe value
SalaryData['fnlwgt'][SalaryData['fnlwgt']>600000] = 599629
# Finding nearest values to 40000 mark
SalaryData['capital_gain'][SalaryData['capital_gain']>40000].sort_values()
Above result shows the nearest logical value is 41310, hence, replacing any value above 40000 with it.
# Replacing outliers with nearest possibe value
SalaryData['capital_gain'][SalaryData['capital_gain']>40000] = 41310
# Finding nearest values to 1000 mark
SalaryData['capital.loss'][SalaryData['capital.loss']<1000].sort_values(ascending=False)
The nearest value is 974, hence updating all outliers beyond 1000 with 974
# Replacing outliers with nearest possibe value
SalaryData['capital.loss'][SalaryData['capital.loss']>1000] = 974
The distribution has improved after the outlier treatment. There is still a tail but it is thick, that means there are many values in that range, hence, it is acceptable.
SalaryData.hist(['fnlwgt','capital_gain','capital.loss'], figsize=(18,5))
Missing values are treated for each column separately.
If a column has more than 30% data missing, then missing value treatment cannot be done. That column must be rejected because too much information is missing.
There are below options for treating missing values in data.
# Finding how many missing values are there for each column
SalaryData.isnull().sum()
There are no missing values in the data!
Now its time to finally choose the best columns(Features) which are correlated to the Target variable. This can be done directly by measuring the correlation values or ANOVA/Chi-Square tests. However, it is always helpful to visualize the relation between the Target variable and each of the predictors to get a better sense of data.
I have listed below the techniques used for visualizing relationship between two variables as well as measuring the strength statistically.
In this case study the Target variable is categorical, hence below two scenarios will be present
When the target variable is Categorical and the predictor variable is Continuous we analyze the relation using bar plots/Boxplots and measure the strength of relation using Anova test
# Box plots for Categorical Target Variable "SalaryGT50K" and continuous predictors
ContinuousColsList=['age','hours_per_week','fnlwgt','capital_gain','capital.loss']
import matplotlib.pyplot as plt
fig, PlotCanvas=plt.subplots(nrows=1, ncols=len(ContinuousColsList), figsize=(18,5))
# Creating box plots for each continuous predictor against the Target Variable "SalaryGT50K"
for PredictorCol , i in zip(ContinuousColsList, range(len(ContinuousColsList))):
SalaryData.boxplot(column=PredictorCol, by='SalaryGT50K', figsize=(5,5), vert=True, ax=PlotCanvas[i])
What should you look for in these box plots?
These plots gives an idea about the data distribution of continuous predictor in the Y-axis for each of the category in the X-Axis.
If the distribution looks similar for each category(Boxes are in the same line), that means the the continuous variable has NO effect on the target variable. Hence, the variables are not correlated to each other.
For example, look at the first chart "fnlwgt" Vs "SalaryGT50K". The boxes are in the same line! It means that people who have income greater than 50K have no dependency on the final weight given to the population in their area. Hence, I cannot distinguish between approval and rejection based on the fnlwht. So this column is NOT correlated with the SalaryGT50K.
The other three charts exhibit opposite characteristics. Means the the data distribution is different(the boxes are not in same line!) for each category of salary. It hints that these variables might be correlated with SalaryGT50K.
We confirm this by looking at the results of ANOVA test below
Analysis of variance(ANOVA) is performed to check if there is any relationship between the given continuous and categorical variable
# Defining a function to find the statistical relationship with all the categorical variables
def FunctionAnova(inpData, TargetVariable, ContinuousPredictorList):
from scipy.stats import f_oneway
# Creating an empty list of final selected predictors
SelectedPredictors=[]
print('##### ANOVA Results ##### \n')
for predictor in ContinuousPredictorList:
CategoryGroupLists=inpData.groupby(TargetVariable)[predictor].apply(list)
AnovaResults = f_oneway(*CategoryGroupLists)
# If the ANOVA P-Value is <0.05, that means we reject H0
if (AnovaResults[1] < 0.05):
print(predictor, 'is correlated with', TargetVariable, '| P-Value:', AnovaResults[1])
SelectedPredictors.append(predictor)
else:
print(predictor, 'is NOT correlated with', TargetVariable, '| P-Value:', AnovaResults[1])
return(SelectedPredictors)
# Calling the function to check which categorical variables are correlated with target
ContinuousVariables=['age','hours_per_week','fnlwgt','capital_gain','capital.loss']
FunctionAnova(inpData=SalaryData, TargetVariable='SalaryGT50K', ContinuousPredictorList=ContinuousVariables)
The results of ANOVA confirm our visual analysis using box plots above.
Final selected Continuous columns:
'age', 'hours_per_week', 'capital_gain', 'capital.loss'
When the target variable is Categorical and the predictor is also Categorical then we explore the correlation between them visually using barplots and statistically using Chi-square test
# Cross tablulation between two categorical variables
CrossTabResult=pd.crosstab(index=SalaryData['marital_status'], columns=SalaryData['SalaryGT50K'])
CrossTabResult
# Visual Inference using Grouped Bar charts
CategoricalColsList=['workclass', 'education', 'marital_status','occupation',
'relationship', 'race', 'sex']
import matplotlib.pyplot as plt
fig, PlotCanvas=plt.subplots(nrows=len(CategoricalColsList), ncols=1, figsize=(10,70))
# Creating Grouped bar plots for each categorical predictor against the Target Variable "SalaryGT50K"
for CategoricalCol , i in zip(CategoricalColsList, range(len(CategoricalColsList))):
CrossTabResult=pd.crosstab(index=SalaryData[CategoricalCol], columns=SalaryData['SalaryGT50K'])
CrossTabResult.plot.bar(color=['lightblue','green'], ax=PlotCanvas[i], title=CategoricalCol+' Vs '+'SalaryGT50K')
What to look for in these grouped bar charts?
These grouped bar charts show the frequency in the Y-Axis and the category in the X-Axis. If the ratio of bars is similar across all categories, then the two columns are not correlated.
On the other hand, look at the marital_status vs SalaryGT50K plot. The bars are different for each category, Hence, two columns are correlated with each other.
We confirm this analysis in below section by using Chi-Square Tests.
Chi-Square test is conducted to check the correlation between two categorical variables
# Writing a function to find the correlation of all categorical variables with the Target variable
def FunctionChisq(inpData, TargetVariable, CategoricalVariablesList):
from scipy.stats import chi2_contingency
# Creating an empty list of final selected predictors
SelectedPredictors=[]
for predictor in CategoricalVariablesList:
CrossTabResult=pd.crosstab(index=inpData[TargetVariable], columns=inpData[predictor])
ChiSqResult = chi2_contingency(CrossTabResult)
# If the ChiSq P-Value is <0.05, that means we reject H0
if (ChiSqResult[1] < 0.05):
print(predictor, 'is correlated with', TargetVariable, '| P-Value:', ChiSqResult[1])
SelectedPredictors.append(predictor)
else:
print(predictor, 'is NOT correlated with', TargetVariable, '| P-Value:', ChiSqResult[1])
return(SelectedPredictors)
CategoricalVariables=['workclass', 'education', 'marital_status','occupation',
'relationship', 'race', 'sex']
# Calling the function
FunctionChisq(inpData=SalaryData,
TargetVariable='SalaryGT50K',
CategoricalVariablesList= CategoricalVariables)
Finally selected Categorical variables:
'workclass', 'education', 'marital_status', 'occupation', 'relationship', 'race', 'sex'
Based on the above tests, selecting the final columns for machine learning
Instead of original "education" column, I am selecting the "education_num". Which represents the ordinal property of the data.
SelectedColumns=['workclass', 'education_num', 'marital_status', 'occupation',
'relationship', 'race', 'sex','age', 'hours_per_week',
'capital_gain', 'capital.loss']
# Selecting final columns
DataForML=SalaryData[SelectedColumns]
DataForML.head()
# Saving this final data for reference during deployment
DataForML.to_pickle('DataForML.pkl')
List of steps performed on predictor variables before data can be used for machine learning
In this data there is no Ordinal categorical variable.
DataForML['sex'].unique()
# Converting the binary nominal variable sex to numeric
# Notice the space in the values!! The data was like that
DataForML['sex'].replace({' Female':0, ' Male':1}, inplace=True)
# Treating all the nominal variables at once using dummy variables
DataForML_Numeric=pd.get_dummies(DataForML)
# Adding Target Variable to the data
DataForML_Numeric['SalaryGT50K']=SalaryData['SalaryGT50K']
# Printing sample rows
DataForML_Numeric.head()
We dont use the full data for creating the model. Some data is randomly selected and kept aside for checking how good the model is. This is known as Testing Data and the remaining data is called Training data on which the model is built. Typically 70% of data is used as Training data and the rest 30% is used as Tesing data.
# Printing all the column names for our reference
DataForML_Numeric.columns
# Separate Target Variable and Predictor Variables
TargetVariable='SalaryGT50K'
Predictors=['education_num', 'age', 'hours_per_week', 'capital_gain',
'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
'workclass_ State-gov', 'workclass_ Without-pay',
'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
'marital_status_ Married-civ-spouse',
'marital_status_ Married-spouse-absent',
'marital_status_ Never-married', 'marital_status_ Separated',
'marital_status_ Widowed', 'occupation_ ?', 'occupation_ Adm-clerical',
'occupation_ Armed-Forces', 'occupation_ Craft-repair',
'occupation_ Exec-managerial', 'occupation_ Farming-fishing',
'occupation_ Handlers-cleaners', 'occupation_ Machine-op-inspct',
'occupation_ Other-service', 'occupation_ Priv-house-serv',
'occupation_ Prof-specialty', 'occupation_ Protective-serv',
'occupation_ Sales', 'occupation_ Tech-support',
'occupation_ Transport-moving', 'relationship_ Husband',
'relationship_ Not-in-family', 'relationship_ Other-relative',
'relationship_ Own-child', 'relationship_ Unmarried',
'relationship_ Wife', 'race_ Amer-Indian-Eskimo',
'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White',
'sex']
X=DataForML_Numeric[Predictors].values
y=DataForML_Numeric[TargetVariable].values
# Split the data into training and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=428)
You can choose not to run this step if you want to compare the resultant accuracy of this transformation with the accuracy of raw data.
However, if you are using KNN or Neural Networks, then this step becomes necessary.
### Sandardization of data ###
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Choose either standardization or Normalization
# On this data Min Max Normalization produced better results
# Choose between standardization and MinMAx normalization
#PredictorScaler=StandardScaler()
PredictorScaler=MinMaxScaler()
# Storing the fit object for later reference
PredictorScalerFit=PredictorScaler.fit(X)
# Generating the standardized values of X
X=PredictorScalerFit.transform(X)
# Split the data into training and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Sanity check for the sampled data
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
# Logistic Regression
from sklearn.linear_model import LogisticRegression
# choose parameter Penalty='l1' or C=1
# choose different values for solver 'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'
clf = LogisticRegression(C=1,penalty='l2', solver='newton-cg')
# Printing all the parameters of logistic regression
# print(clf)
# Creating the model on Training Data
LOG=clf.fit(X_train,y_train)
prediction=LOG.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(LOG, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
#Decision Trees
from sklearn import tree
#choose from different tunable hyper parameters
clf = tree.DecisionTreeClassifier(max_depth=6,criterion='entropy')
# Printing all the parameters of Decision Trees
print(clf)
# Creating the model on Training Data
DTree=clf.fit(X_train,y_train)
prediction=DTree.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(DTree.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(DTree, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
# Installing the required library for plotting the decision tree
#!pip install dtreeplt
from dtreeplt import dtreeplt
dtree = dtreeplt(model=clf, feature_names=Predictors, target_names=TargetVariable)
fig = dtree.view()
currentFigure=plt.gcf()
currentFigure.set_size_inches(100,20)
# Double click on the graph to zoom in
# Random Forest (Bagging of multiple Decision Trees)
from sklearn.ensemble import RandomForestClassifier
# Choose different hyperparameter values of max_depth, n_estimators and criterion to tune the model
clf = RandomForestClassifier(max_depth=5, n_estimators=100,criterion='gini')
# Printing all the parameters of Random Forest
print(clf)
# Creating the model on Training Data
RF=clf.fit(X_train,y_train)
prediction=RF.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(RF, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(RF.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
# PLotting a single Decision Tree from Random Forest
from dtreeplt import dtreeplt
dtree = dtreeplt(model=clf.estimators_[4], feature_names=Predictors, target_names=TargetVariable)
fig = dtree.view()
currentFigure=plt.gcf()
currentFigure.set_size_inches(100,20)
# Double click on the graph to zoom in
# Adaboost
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
# Choosing Decision Tree with 1 level as the weak learner
DTC=DecisionTreeClassifier(max_depth=1)
clf = AdaBoostClassifier(n_estimators=100, base_estimator=DTC ,learning_rate=0.1)
# Printing all the parameters of Adaboost
print(clf)
# Creating the model on Training Data
AB=clf.fit(X_train,y_train)
prediction=AB.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(AB, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(AB.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
# PLotting 5th single Decision Tree from Adaboost
from dtreeplt import dtreeplt
dtree = dtreeplt(model=clf.estimators_[5], feature_names=Predictors, target_names=TargetVariable)
fig = dtree.view()
# Xtreme Gradient Boosting (XGBoost)
from xgboost import XGBClassifier
clf=XGBClassifier(max_depth=2, learning_rate=0.1, n_estimators=200, objective='binary:logistic', booster='gbtree')
# Printing all the parameters of XGBoost
print(clf)
# Creating the model on Training Data
XGB=clf.fit(X_train,y_train)
prediction=XGB.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(XGB, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(XGB.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
from xgboost import plot_tree
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(20, 8))
plot_tree(XGB, num_trees=10, ax=ax)
# K-Nearest Neighbor(KNN)
from sklearn.neighbors import KNeighborsClassifier
clf = KNeighborsClassifier(n_neighbors=3)
# Printing all the parameters of KNN
print(clf)
# Creating the model on Training Data
KNN=clf.fit(X_train,y_train)
prediction=KNN.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(KNN, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
# Plotting the feature importance for Top 10 most important columns
# There is no built-in method to get feature importance in KNN
# Support Vector Machines(SVM)
from sklearn import svm
clf = svm.SVC(C=3, kernel='rbf', gamma=0.1)
# Printing all the parameters of KNN
print(clf)
# Creating the model on Training Data
SVM=clf.fit(X_train,y_train)
prediction=SVM.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(SVM, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
# Plotting the feature importance for Top 10 most important columns
# The built in attribute SVM.coef_ works only for linear kernel
%matplotlib inline
#feature_importances = pd.Series(SVM.coef_[0], index=Predictors)
#feature_importances.nlargest(10).plot(kind='barh')
# Naive Bays
from sklearn.naive_bayes import GaussianNB, MultinomialNB
# GaussianNB is used in Binomial Classification
# MultinomialNB is used in multi-class classification
clf = GaussianNB()
#clf = MultinomialNB()
# Printing all the parameters of Naive Bayes
print(clf)
NB=clf.fit(X_train,y_train)
prediction=NB.predict(X_test)
# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))
# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(NB, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
Based on the above trials you select that algorithm which produces the best average accuracy. In this case, multiple algorithms have produced similar kind of average accuracy. Hence, we can choose any one of them.
I am choosing Logistic Regression as the final model since it is very fast for this data!
In order to deploy the model we follow below steps
Its beneficial to keep lesser number of predictors for the model while deploying it in production. The lesser predictors you keep, the better because, the model will be less dependent hence, more stable.
This is important specially when the data is high dimensional(too many predictor columns).
In this data, the most important predictor variables are 'age', 'education_num', 'hours_per_week','capital_gain', 'capital.loss', 'workclass', and 'marital_status'. As these are consistently on top of the variable importance chart for every algorithm. Hence choosing these as final set of predictor variables.
# Separate Target Variable and Predictor Variables
TargetVariable='SalaryGT50K'
# Selecting the final set of predictors for the deployment
# Based on the variable importance charts of multiple algorithms above
Predictors=['education_num', 'age', 'hours_per_week', 'capital_gain',
'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
'workclass_ State-gov', 'workclass_ Without-pay',
'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
'marital_status_ Married-civ-spouse',
'marital_status_ Married-spouse-absent',
'marital_status_ Never-married', 'marital_status_ Separated',
'marital_status_ Widowed']
X=DataForML_Numeric[Predictors].values
y=DataForML_Numeric[TargetVariable].values
### Sandardization of data ###
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Choose either standardization or Normalization
# On this data Min Max Normalization produced better results
# Choose between standardization and MinMAx normalization
#PredictorScaler=StandardScaler()
PredictorScaler=MinMaxScaler()
# Storing the fit object for later reference
PredictorScalerFit=PredictorScaler.fit(X)
# Generating the standardized values of X
X=PredictorScalerFit.transform(X)
print(X.shape)
print(y.shape)
# Logistic Regression
from sklearn.linear_model import LogisticRegression
# choose parameter Penalty='l1' or C=1
# choose different values for solver 'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'
# Using the Logistic Regression algorithm with final hyperparamters
clf = LogisticRegression(C=1,penalty='l2', solver='newton-cg')
# Training the model on 100% Data available
FinalLogisticModel=clf.fit(X,y)
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score
# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(FinalLogisticModel, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
import pickle
import os
# Saving the Python objects as serialized files can be done using pickle library
# Here let us save the Final model
with open('FinalLogisticModel.pkl', 'wb') as fileWriteStream:
pickle.dump(FinalLogisticModel, fileWriteStream)
# Don't forget to close the filestream!
fileWriteStream.close()
print('pickle file of Predictive Model is saved at Location:',os.getcwd())
# This Function can be called from any from any front end tool/website
def PredictSalaryBand(InputData):
import pandas as pd
Num_Inputs=InputData.shape[0]
# Making sure the input data has same columns as it was used for training the model
# Also, if standardization/normalization was done, then same must be done for new input
# Appending the new data with the Training data
DataForML=pd.read_pickle('DataForML.pkl')
InputData=InputData.append(DataForML)
# Generating dummy variables for rest of the nominal variables
InputData=pd.get_dummies(InputData)
# Maintaining the same order of columns as it was during the model training
Predictors=['education_num', 'age', 'hours_per_week', 'capital_gain',
'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
'workclass_ State-gov', 'workclass_ Without-pay',
'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
'marital_status_ Married-civ-spouse',
'marital_status_ Married-spouse-absent',
'marital_status_ Never-married', 'marital_status_ Separated',
'marital_status_ Widowed']
# Generating the input values to the model
X=InputData[Predictors].values[0:Num_Inputs]
# Generating the standardized values of X since it was done while model training also
X=PredictorScalerFit.transform(X)
# Loading the Function from pickle file
import pickle
with open('FinalLogisticModel.pkl', 'rb') as fileReadStream:
LogisticModel=pickle.load(fileReadStream)
# Don't forget to close the filestream!
fileReadStream.close()
# Genrating Predictions
Prediction=LogisticModel.predict(X)
PredictedStatus=pd.DataFrame(Prediction, columns=['Predicted Status'])
return(PredictedStatus)
# Calling the function for some loan applications
NewEmployeeDetails=pd.DataFrame(
data=[[39,13,40,15024,0,'State-gov','Never-married'],
[39,13,40,2174,0,'Private','Never-married']],
columns=['age', 'education_num', 'hours_per_week','capital_gain',
'capital.loss', 'workclass', 'marital_status'])
print(NewEmployeeDetails)
# Calling the Function for prediction
PredictSalaryBand(InputData= NewEmployeeDetails)
The Function PredictSalaryBand can be used to produce the predictions for one or more loan applications at a time. Hence, it can be scheduled using a batch job or cron job to run every night and generate predictions for all the loan applications available in the system.
# Creating the function which can take inputs and return predictions
def FunctionSalaryBandPrediction(inp_age, inp_education_num , inp_hours_per_week, inp_capital_gain,
inp_capital_loss, inp_workclass, inp_marital_status):
# Creating a data frame for the model input
SampleInputData=pd.DataFrame(
data=[[inp_age, inp_education_num , inp_hours_per_week, inp_capital_gain,
inp_capital_loss, inp_workclass, inp_marital_status]],
columns=['age', 'education_num', 'hours_per_week','capital_gain',
'capital.loss', 'workclass', 'marital_status'])
# Calling the function defined above using the input parameters
Predictions=PredictSalaryBand(InputData= SampleInputData)
# Returning the predictions
return(Predictions.to_json())
# Function call
FunctionSalaryBandPrediction(inp_age=39,
inp_education_num =13,
inp_hours_per_week=40,
inp_capital_gain=15024,
inp_capital_loss=0,
inp_workclass='State-gov',
inp_marital_status='Never-married',
)
# Installing the flask library required to create the API
#!pip install flask
from flask import Flask, request, jsonify
import pickle
import pandas as pd
import numpy
app = Flask(__name__)
@app.route('/get_salary_band_prediction', methods=["GET"])
def get_salary_band_prediction():
try:
# Getting the paramters from API call
age_value = float(request.args.get('age'))
education_num_value = float(request.args.get('education_num'))
hours_per_week_value=float(request.args.get('hours_per_week'))
capital_gain_value=float(request.args.get('capital_gain'))
capital_loss_value = float(request.args.get('capital_loss'))
workclass_value = request.args.get('workclass')
marital_status_value = request.args.get('marital_status')
# Calling the funtion to get predictions
prediction_from_api=FunctionSalaryBandPrediction(
inp_age=age_value,
inp_education_num =education_num_value,
inp_hours_per_week=hours_per_week_value,
inp_capital_gain=capital_gain_value,
inp_capital_loss=capital_loss_value,
inp_workclass=workclass_value,
inp_marital_status=marital_status_value,
)
return (prediction_from_api)
except Exception as e:
return('Something is not right!:'+str(e))
import os
if __name__ =="__main__":
# Hosting the API in localhost
app.run(host='127.0.0.1', port=8080, threaded=True, debug=True, use_reloader=False)
# Interrupt kernel to stop the API
This URL can be called by any front end application like Java, Tableau etc. Once the parameters are passed to it, the predictions will be generated.